import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart';

import '../../common/index.dart';

class MessageListPage extends ConsumerStatefulWidget {
  const MessageListPage({super.key});

  @override
  ConsumerState<MessageListPage> createState() => _MessageListPageState();
}

class _MessageListPageState extends ConsumerState<MessageListPage>
    with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    // 添加生命周期监听器
    WidgetsBinding.instance.addObserver(this);
    // 页面初始化时自动加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadMessageList();
    });
  }

  @override
  void dispose() {
    // 移除生命周期监听器
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用从后台回到前台时，刷新消息列表
    if (state == AppLifecycleState.resumed) {
      _loadMessageList();
    }
  }

  Future<void> _loadMessageList() async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser != null) {
      final messageNotifier = ref.read(messageProvider.notifier);
      await messageNotifier.loadConversations(currentUser.id);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: SizedBox(
          width: 100.w,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'message',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 24.sp,
                  fontFamily: 'Port',
                  fontWeight: FontWeight.w400,
                  height: 0.83.h,
                ),
              ),
              SizedBox(width: 3.w),
              SvgPicture.asset(MyIcons.star, width: 8.w, height: 8.h),
              SvgPicture.asset(
                MyIcons.star,
                width: 5.w,
                height: 5.h,
              ).padding(top: 12.h),
            ],
          ),
        ),
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.messageBg),
            fit: BoxFit.fill,
          ),
        ),
        child: Column(
          children: [
            SizedBox(height: 114.h),
            Expanded(
              child: Container(
                width: 375.w,
                padding: EdgeInsets.only(top: 35.h),
                decoration: ShapeDecoration(
                  color: Colors.black,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                      topRight: Radius.circular(48.r),
                    ),
                  ),
                ),
                child: Consumer(
                  builder: (context, ref, child) {
                    final messageState = ref.watch(messageProvider);
                    final currentUser = ref.watch(currentUserProvider);
                    final conversations = messageState.conversations;
                    final isLoading = messageState.isLoading;
                    final error = messageState.error;

                    // 监听用户状态变化，自动重新加载消息列表
                    ref.listen<UserEntity?>(currentUserProvider, (
                      previous,
                      next,
                    ) {
                      if (previous?.id != next?.id) {
                        // 用户发生变化时，重新加载消息列表
                        WidgetsBinding.instance.addPostFrameCallback((_) {
                          if (mounted) {
                            _loadMessageList();
                          }
                        });
                      }
                    });

                    if (currentUser == null) {
                      return Center(
                        child: Text(
                          'Please login first',
                          style: TextStyle(
                            color: Colors.white.withValues(alpha: 0.6),
                            fontSize: 16.sp,
                          ),
                        ),
                      );
                    }

                    if (error != null) {
                      return Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              'Error: $error',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 14.sp,
                              ),
                              textAlign: TextAlign.center,
                            ),
                            SizedBox(height: 16.h),
                            ElevatedButton(
                              onPressed: _loadMessageList,
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Color(0xFFF8AD51),
                                foregroundColor: Colors.black,
                              ),
                              child: Text('Retry'),
                            ),
                          ],
                        ),
                      );
                    }

                    if (isLoading && conversations.isEmpty) {
                      return Center(
                        child: CircularProgressIndicator(
                          color: Color(0xFFF8AD51),
                        ),
                      );
                    }

                    if (conversations.isEmpty) {
                      return Center(
                        child: Text(
                          'No conversations yet',
                          style: TextStyle(
                            color: Colors.white.withValues(alpha: 0.6),
                            fontSize: 16.sp,
                          ),
                        ),
                      );
                    }

                    return RefreshIndicator(
                      onRefresh: _loadMessageList,
                      child: ListView.builder(
                        padding: EdgeInsets.symmetric(horizontal: 5.w),
                        itemCount: conversations.length,
                        itemBuilder: (context, index) {
                          final message = conversations[index];
                          return _buildMessageItem(message);
                        },
                      ),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMessageItem(MessageEntity message) {
    final currentUser = ref.watch(currentUserProvider);
    if (currentUser == null) return SizedBox.shrink();

    // 确定对话伙伴的ID
    final partnerId = message.senderId == currentUser.id
        ? message.receiverId
        : message.senderId;

    return Consumer(
      builder: (context, ref, child) {
        return FutureBuilder<UserEntity?>(
          future: UserService.getUserById(partnerId),
          builder: (context, snapshot) {
            // 在加载用户信息时显示默认信息
            final partnerUser = snapshot.data;
            final partnerName = partnerUser?.username ?? 'Loading...';

            // 格式化时间
            final timeStr = _formatTime(message.timestamp);

            // 格式化消息内容
            final contentPreview = _formatMessageContent(message, currentUser);

            // 计算未读消息数量（只计算对方发给我的未读消息）
            final unreadCount = _getUnreadCountForPartner(
              partnerId,
              currentUser,
            );

            return InkWell(
              onTap: () =>
                  _navigateToChat(partnerId, partnerName, currentUser.id),
              splashColor: Colors.white.withValues(alpha: 0.1),
              highlightColor: Colors.white.withValues(alpha: 0.05),
              child: Container(
                width: double.infinity,
                height: 70.h,
                margin: EdgeInsets.only(bottom: 20.h),
                padding: EdgeInsets.symmetric(vertical: 8.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      child: Row(
                        children: [
                          // 用户头像
                          Container(
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border: Border.all(
                                color: const Color(0xFFF8AD51),
                                width: 1.w,
                              ),
                            ),
                            child: UserAvatar(
                              radius: 24.w, // 48.w / 2 = 24.w
                              avatarPath: partnerUser?.avatar,
                              fallbackAsset: MyImages.mark,
                            ),
                          ),
                          SizedBox(width: 12.w),
                          // 用户名和消息预览
                          Expanded(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  partnerName,
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 14.sp,
                                    fontFamily: 'PingFang SC',
                                    fontWeight: FontWeight.w600,
                                  ),
                                  overflow: TextOverflow.ellipsis,
                                ),
                                SizedBox(height: 4.h),
                                Text(
                                  contentPreview,
                                  style: TextStyle(
                                    color: Colors.white.withValues(alpha: 0.7),
                                    fontSize: 11.sp,
                                    fontFamily: 'PingFang SC',
                                    fontWeight: FontWeight.w500,
                                  ),
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 1,
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    // 时间和未读消息数量
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Text(
                          timeStr,
                          style: TextStyle(
                            color: Colors.white.withValues(alpha: 0.6),
                            fontSize: 12.sp,
                            fontFamily: 'PingFang SC',
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        if (unreadCount > 0) ...[
                          SizedBox(height: 4.h),
                          Container(
                            constraints: BoxConstraints(
                              minWidth: 20.w,
                              minHeight: 20.h,
                            ),
                            padding: EdgeInsets.symmetric(
                              horizontal: 6.w,
                              vertical: 2.h,
                            ),
                            decoration: ShapeDecoration(
                              color: const Color(0xFFF8AD51),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10.r),
                              ),
                            ),
                            child: Text(
                              unreadCount > 99 ? '99+' : unreadCount.toString(),
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                color: const Color(0xFF212121),
                                fontSize: 10.sp,
                                fontFamily: 'PingFang SC',
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  /// 格式化时间显示
  String _formatTime(DateTime timestamp) {
    final now = DateTime.now();
    final difference = now.difference(timestamp);

    if (difference.inDays == 0) {
      // 今天，显示时间
      return DateFormat('HH:mm').format(timestamp);
    } else if (difference.inDays == 1) {
      // 昨天
      return 'Yesterday';
    } else if (difference.inDays < 7) {
      // 一周内，显示星期
      return DateFormat('EEEE').format(timestamp);
    } else {
      // 超过一周，显示日期
      return DateFormat('MM/dd').format(timestamp);
    }
  }

  /// 格式化消息内容预览
  String _formatMessageContent(MessageEntity message, UserEntity currentUser) {
    String prefix = '';
    if (message.senderId == currentUser.id) {
      prefix = 'You: ';
    }

    String content = '';
    if (message.type == MessageType.text) {
      content = message.content;
    } else if (message.type == MessageType.image) {
      content = '[Image]';
    }

    final fullContent = prefix + content;

    // 限制长度
    if (fullContent.length > 30) {
      return '${fullContent.substring(0, 30)}...';
    }
    return fullContent;
  }

  /// 获取与特定伙伴的未读消息数量
  int _getUnreadCountForPartner(String partnerId, UserEntity currentUser) {
    // 监听MessageProvider的状态变化，确保实时更新
    final messageState = ref.watch(messageProvider);

    // 从缓存的对话中计算未读消息数
    final conversationKey = _getConversationKey(currentUser.id, partnerId);
    final conversationMessages =
        messageState.conversationCache[conversationKey] ?? [];

    // 计算对方发给我的未读消息数量
    return conversationMessages
        .where(
          (message) =>
              message.senderId == partnerId &&
              message.receiverId == currentUser.id &&
              !message.isRead,
        )
        .length;
  }

  /// 生成对话缓存键（与MessageProvider中的逻辑保持一致）
  String _getConversationKey(String userId1, String userId2) {
    final sortedIds = [userId1, userId2]..sort();
    return '${sortedIds[0]}_${sortedIds[1]}';
  }

  /// 导航到聊天页面
  void _navigateToChat(
    String partnerId,
    String partnerName,
    String currentUserId,
  ) {
    // 标记对话为已读
    ref
        .read(messageProvider.notifier)
        .markConversationAsRead(currentUserId, partnerId);
    // 使用GoRouter导航到聊天页面
    context.navigateTo('${AppRoutes.chat}/$partnerId');
  }
}
